import Request from 'luch-request'
import website from '@/common/config.js'
import store from '@/store'

const request = new Request()

request.setConfig(config => {
  config.baseURL = website.baseUrl
  if (!('content-type' in config.header)) {
    config.header['content-type'] = 'application/x-www-form-urlencoded'
  }
  return config
})

request.interceptors.request.use(config => {
  const token = uni.getStorageSync('token')
  if (token) {
    config.header.token = token
  }
  // if (!token) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
  //   return Promise.reject(config)
  // }
  return config
})

request.interceptors.response.use(
  res => {
    //获取状态码
    const status = res.data.code || res.statusCode
    const statusWhiteList = website.statusWhiteList || []
    const message = res.data.msg || res.data.error_description || '未知错误'

    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res)
    //如果是401则跳转到登录页面
    if (status === 401) {
      uni.showToast({ title: message })
      store.dispatch('FedLogOut').then(() => uni.navigateTo({ url: '/pages/login/index' }))
      return Promise.reject(message)
    }
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      uni.showToast({ title: message, icon: 'error' })
      return Promise.reject(message)
    }
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

export default request
